<template>
    <div>
        <!-- 搜索卡片 -->
        <el-card style="height: 70px;">
            <el-form :inline="true" class="search">
                <el-form-item label="用户名:">
                    <el-input placeholder="请输入用户名" v-model="inputUsername"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :disabled="inputUsername?false:true" @click="Search">搜索</el-button>
                    <el-button type="primary" @click="reset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card style="margin-top: 10px;">
            <el-button @click="AddUser" type="primary">添加用户</el-button>
            <el-button type="danger" :disabled="arrRoleSelect.length?false:true" @click="deleteManyUser">批量删除</el-button>
            <!-- 展示 -->
            <el-table  @selection-change="SelectionChange" border style="width: 100%" :data="userArr">
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column  label="#" type="index" width="55" align="center"></el-table-column>
                <el-table-column  prop="id" label="id"  align="center"></el-table-column>
                <el-table-column  prop="username" label="用户名字"  align="center" show-overflow-tooltip></el-table-column>
                <el-table-column  prop="name" label="用户名称"  align="center" show-overflow-tooltip></el-table-column>
                <el-table-column  prop="roleName" label="用户角色"  align="center" show-overflow-tooltip></el-table-column>
                <el-table-column  prop="createTime" label="创建时间"  align="center" show-overflow-tooltip></el-table-column>
                <el-table-column  prop="updateTime" label="更新时间"  align="center" show-overflow-tooltip></el-table-column>
                <el-table-column  label="操作" width="300" align="center">
                    <template #="{row}">
                        <el-button @click="EdiitRole(row)" type="primary" icon="Avatar" size="small">分配角色</el-button>
                        <el-button @click="EditUser(row)" type="primary" icon="Edit" size="small">编辑</el-button>
                        
                        <el-popconfirm :title="`你确定要删除${row.username}吗?`"
                        @confirm="DeleteUser(row)"  >
                            <template #reference>
                                <el-button type="primary" icon="Delete" size="small">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
              
            </el-table>
            <!-- 分页器-->
            <el-pagination
                v-model:current-page="pageNow"
                v-model:page-size="pageSize"
                :page-sizes="[5,7,9,11]"
                :background="true"
                layout=" prev, pager, next, jumper,->, sizes,total"
                :total="totle"
                @current-change="getHasUserInfo(pageNow)"
                @size-change="SizeChange"
                /> 
        </el-card>
        <!-- 添加用户|修改用户抽屉 -->
        <el-drawer v-model="drawer">
            <template #header>
                <h4>{{ userParmas.id?'修改用户':'添加用户' }}</h4>
            </template>
            <template #default>
                <el-form :model="userParmas" ref="formRef" :rules="rules" >
                    <el-form-item label="用户名称" prop="username">
                        <el-input v-model="userParmas.username"  placeholder="请输入用户名称"></el-input>
                    </el-form-item>
                    <el-form-item label="用户昵称" prop="name" >
                        <el-input v-model="userParmas.name" placeholder="请输入用户昵称"></el-input>
                    </el-form-item>
                    <el-form-item label="用户密码" prop="password" v-if="!userParmas.id">
                        <el-input v-model="userParmas.password"  placeholder="请输入用户密码"></el-input>
                    </el-form-item>
                    
                </el-form>
            </template>
            <template #footer>
                <div style="flex: auto">
                    <el-button @click="cancelClick">取消</el-button>
                    <el-button type="primary" @click="confirmClick">确定</el-button>
                </div>
            </template>
        </el-drawer>
        <!-- 分配角色抽屉 -->
        <el-drawer v-model="drawer1" >
            <template #header>
                <h4>分配角色</h4>
            </template>
            <template #default>
                <el-form>
                    <!-- 用户名称 -->
                    <el-form-item label="用户名称">
                        <el-input v-model="userParmas.username" :disabled="true"></el-input>
                    </el-form-item>
                    <!-- 角色分配 -->
                    <el-form-item label="分配角色">
                        <!-- 全选按钮 -->
                        <el-checkbox
                            v-model="checkAll"
                            :indeterminate="isIndeterminate"
                            @change="handleCheckAllChange"
                        >全选</el-checkbox>
                        <!-- 单选按钮 -->
                        <el-checkbox-group
                            v-model="RoleArr"
                            @change="handleCheckedCitiesChange"
                        >
                            <el-checkbox v-for="(role) in allRoleArr" :key="role.id" :value="role">
                            {{ role.roleName }}
                            </el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </el-form>
                
            </template>
            <template #footer>
            <div style="flex: auto">
                <el-button @click="cancelClickRole">取消</el-button>
                <el-button type="primary" @click="confirmClickRole">确定</el-button>
            </div>
            </template>
        </el-drawer>
    </div>
</template>

<script setup lang='ts'>
import { nextTick, onMounted, reactive, ref } from 'vue';
import type {ResponseUserData,Records,Role,ResponseRole,ParmasSetRoleData} from '@/api/acl/user/type'
import {reqGetUserInfo,reqAddOrUpdate,reqGetRoleAndAllRole,reqSetRole,reqDeleteOneUseer,reqDeleteManyUser} from'@/api/acl/user/index'
import { ElMessage } from 'element-plus';
import uselayoutStore from '@/store/modules/stting'
//当前页
const pageNow=ref<number>(1)
//每页个数
const pageSize=ref<number>(5)
//用户数据总数
const totle=ref<number>()
//存储用户信息的数组
const userArr=ref<Records[]>([])
//控制新增|修改用户 抽屉显隐
const drawer=ref<boolean>(false)
//控制分配角色 抽屉显隐
const drawer1=ref(false)
//存储更新|添加的用户信息
const userParmas=reactive<Records>({
    username:'',
    name:'',
    password:''
})
//控制全选按钮全勾选
const checkAll=ref<boolean>(false)
//不确定的样式
const isIndeterminate = ref<boolean>(true)

//form实例
const formRef=ref()
//存储当前用户角色的数组
let RoleArr=ref<Role[]>([])
//存储全部角色的数组
let allRoleArr=ref<Role[]>([])
//存储表格选择项的数据
let arrRoleSelect=ref<Records[]>([])
//存储搜索的数据
const inputUsername=ref<string>('')
//使用stting仓库的refresh
const uselayoutstore=uselayoutStore()
//挂载时发送一次请求
onMounted(()=>{
    getHasUserInfo()
})

//发送获取用户信息请求
const getHasUserInfo=async(pager:number=1)=>{
    pageNow.value=pager
    let result:ResponseUserData=await reqGetUserInfo(pageNow.value,pageSize.value,inputUsername.value)
    totle.value=result.data.total
    userArr.value=result.data.records   
}
//每页显示条目个数改变时调用
const SizeChange=()=>{
    getHasUserInfo()
}
//新增用户按钮回调
const AddUser=()=>{
    drawer.value=true
    //清空userParmas
    Object.assign(userParmas,{
        id:'',
        username:'',
        name:'',
        password:''
    })
    nextTick(()=>{
        formRef.value.clearValidate('username')
        formRef.value.clearValidate('name')
        formRef.value.clearValidate('password')
    })
}
//编辑按钮回调
const EditUser=(row:Records)=>{
    drawer.value=true
    // 获取用户名称及用户名字
    Object.assign(userParmas,row)
    nextTick(()=>{
        formRef.value.clearValidate('username')
        formRef.value.clearValidate('name')
       
    })
}
//抽取确认按钮回调
const confirmClick=async()=>{
    // 判断表单是否校验通过，通过就放行，不通过就等待
    await formRef.value.validate()
    
    //发送请求
    let result=await reqAddOrUpdate(userParmas)
    if(result.code==200){
        ElMessage({
            type:'success',
            message:userParmas.id?'修改成功':'添加成功'
        })
        //再次刷新页面
        window.location.reload()
    }else{
        ElMessage({
            type:'error',
            message:userParmas.id?'修改失败':'添加失败'
        })
    }
    //隐藏抽屉
    drawer.value=false
    
}
//取消按钮回调
const cancelClick=()=>{
    //隐藏抽屉
    drawer.value=false
}
//用户名称校校验
const validateUsername=(_rule: any, value: any, callback: any)=>{
    if(value.trim().length>1){
        callback()
    }else{
        callback(new Error('用户名称不能小于2位'))
    }
    
}
//名称校验规则
const validateName=(_rule: any, value: any, callback: any)=>{
    if(value.trim().length>=2){
        callback()
    }
    else{
        callback(new Error('名称不能小于2位'))
    }
}
//密码校验规则
const validatePassword=(_rule: any, value: any, callback: any)=>{
    if(value.trim().length>=6&&value.trim().length<=20){
        callback()
    }else{
        callback(new Error('密码需要在6到20位'))
    }

}
//表单校验
const rules={
    username:[{required: true,trigger:'blur',validator: validateUsername}],
    name:[{required: true,trigger:'blur',validator: validateName}],
    password:[{required: true,trigger:'blur',validator: validatePassword}]
}
//分配角色按钮回调
const EdiitRole=async (row:Records)=>{
    
    //存储该用户数据
    Object.assign(userParmas,row)
    //获取全部角色的数组以及当前角色的数组
    let result:ResponseRole=await reqGetRoleAndAllRole((row.id as number))
    if(result.code==200){
        drawer1.value=true
        RoleArr.value=result.data.rawUserInfoList
    
        allRoleArr.value=result.data.rawAllRole
        
    }
    
}
//顶部全选复选框事件
const handleCheckAllChange=(val:boolean)=>{
    console.log(val);
    RoleArr.value=val?allRoleArr.value:[]
    isIndeterminate.value=false
    
}
//底部全部的复选框change事件
const handleCheckedCitiesChange=(value:Role[])=>{
    //获取单选数组的长度
    const checkedCount = value.length
    //顶部复选框的勾选数据
    //代表：勾选上的项目个数与全部的职位个数相等，顶部的复选框勾选上
    checkAll.value = checkedCount === allRoleArr.value.length
    //不确定的样式
    isIndeterminate.value = checkedCount > 0 && checkedCount < allRoleArr.value.length
}

//分配角色取消按钮回调
const cancelClickRole=()=>{
    //隐藏抽屉
    drawer1.value=false
}
//分配角色确定按钮回调
const confirmClickRole=async()=>{
    // 移除null值
    let arr=RoleArr.value.filter(item => item !== null && item !== undefined);
    //获取该用户被分配的角色的id
    let data:ParmasSetRoleData={
        id:(userParmas.id as number ),
        roleIdList:arr.map((item:Role)=>{
            return (item.id as number)
        })
    }
    
    //发送请求
    const result=await reqSetRole(data)
    if(result.code==200){
        ElMessage({
            type:'success',
            message:'分配成功'
        })
        //隐藏抽屉
        drawer1.value=false
        //再次获取用户数据，更新页面
        getHasUserInfo(pageNow.value)
    }else{
        ElMessage({
            type:'error',
            message:'分配失败'
        })
    }
    
}
//在表格里面删除单个用户回调
const DeleteUser=async(row:Records)=>{
    let result=await reqDeleteOneUseer((row.id as number))
    if(result.code==200){
        ElMessage({
            type:'success',
            message:'删除成功'
        })
        getHasUserInfo(userArr.value?pageNow.value:pageNow.value-1)
    }else{
        ElMessage({
            type:'error',
            message:'删除失败'
        })
    }
}
//表格选择项变化触发
const SelectionChange=(value:any)=>{
    arrRoleSelect.value=value
    
}
//批量删除用户
const deleteManyUser=async()=>{
    const roleIdList:number[]=arrRoleSelect.value.map((item)=>{
        return (item.id as number)
    })
    let result=await reqDeleteManyUser(roleIdList)
    if(result.code==200){
        ElMessage({
            type:'success',
            message:'删除成功'
        })
        getHasUserInfo(userArr.value?pageNow.value:pageNow.value-1)
    }else{
        ElMessage({
            type:'error',
            message:'删除失败'
        })
    }

}
//搜索按钮回调
const Search=()=>{
    //发送请求获取搜索数据
    getHasUserInfo()
    //清空输入框
    inputUsername.value=''
}
//重置按钮回调
const reset=()=>{
    //调用stting仓库的刷新
    uselayoutstore.refresh=!uselayoutstore.refresh
}
</script>
<style scoped lang='scss'>
.search{
    display: flex;
    justify-content: space-between;
    align-items: center;
    
}
</style>